<template>
  <div :id="containerId" style="position: relative">

    <!--  ---------------------------- begin 图片左右换位置 ------------------------------------- -->
    <div class="movety-container" :style="{top:top+'px',left:left+'px',display:moveDisplay}"
         style="padding:0 8px;position: absolute;z-index: 91;height: 32px;width: 104px;text-align: center;">
      <div :id="containerId+'-mover'" :class="showMoverTask?'uploadty-mover-mask':'movety-opt'"
           style="margin-top: 12px">
        <a @click="moveLast" style="margin: 0 5px;">
          <a-icon type="arrow-left" style="color: #fff;font-size: 16px"/>
        </a>
        <a @click="moveNext" style="margin: 0 5px;">
          <a-icon type="arrow-right" style="color: #fff;font-size: 16px"/>
        </a>
      </div>
    </div>
    <!--  ---------------------------- end 图片左右换位置 ------------------------------------- -->
 <!-- 上传器 -->
 <uploader
        ref="uploader"
        :autoStart=false
        :file-status-text="fileStatusText"
        :options="options"
        @file-added="onFileAdded"
        @file-success="onFileSuccess"
        @file-error="onFileError"
        class="uploader-ui">
        <uploader-unsupport></uploader-unsupport>
        <uploader-drop>
          <div>
            <uploader-btn id="global-uploader-btn"  ref="uploadBtn">选择文件<i class="el-icon-upload el-icon--right"></i></uploader-btn>
          </div>
        </uploader-drop>
        <uploader-list>           
      </uploader-list>
      </uploader>
    <!-- <a-upload
      name="file"
      :multiple="true"
      :show-upload-list="false"
      :action="uploadAction"
      :headers="headers"
      :data="{'biz':bizPath}"
      :fileList="fileList"
      :beforeUpload="beforeUpload"
      @change="handleChange"
      :disabled="disabled"
      :returnUrl="returnUrl"
      :listType="complistType"
      @preview="handlePreview"
      :class="{'uploadty-disabled':disabled}">
      <template>
        <div v-if="isImageComp">
          <a-icon type="plus"/>
          <div class="ant-upload-text">{{ text }}</div>
        </div>
        <a-button v-else-if="buttonVisible">
          <a-icon type="upload"/>
          {{ text }}
        </a-button>
        <span class="hint">(按住ctrl可选择多个文件)</span>
      </template>
    </a-upload> -->
    <ul class="upload-list">
      <a-spin tip="合并文件中" :spinning="spinning"/>
      <li v-for="(file,index) in fileList">
        <a-row type="flex" style="align-items: center">
          <a-col>
            <div class="file-item">
              <a-icon class="file-delete" type="delete" @click="deleteFile(index)"/>
              <a-icon type="loading" v-if="file.status=='uploading'" />
              <a-icon type="paper-clip"/>
              <span class="file-item-name" :class="file.status+'-file-item'">{{file.name}}</span>
            </div>
            <a-progress v-if="file.status=='uploading'" :percent="file.percent" :strokeWidth="2"
                        :show-info="false"></a-progress>
          </a-col>
          <a-col v-if="file.status=='done'">
            <a-select v-model="file.mediaType" @change="handleFileChange" style="width: 120px;margin-left: 30px">
              <a-select-option value="0">图片</a-select-option>
              <a-select-option value="1">视频</a-select-option>
              <a-select-option value="2">音频</a-select-option>
              <a-select-option value="3">文件</a-select-option>
            </a-select>
          </a-col>
        </a-row>

      </li>
    </ul>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage"/>
    </a-modal>
  </div>
</template>

<script>

  import Vue from 'vue'
  import {ACCESS_TOKEN} from "@/store/mutation-types"
  import {getFileAccessHttpUrl} from '@/api/manage';
  import {isAudioFile, isImgFile, isVideoFile} from "@/utils/xinkeUtil";
  import {getFileItem} from 'ant-design-vue/es/upload/utils';
  import SparkMD5 from 'spark-md5';
import {requestApi} from '@/utils/request1';

const mergeFile = data => {
  const option = {};
    option.isJson = true
    option.data = JSON.stringify(data)
    option.method = 'post'
    option.url = 'api/upload/mergeFile'
    return requestApi(option)
  }



  const FILE_TYPE_ALL = "all"
  const FILE_TYPE_IMG = "image"
  const FILE_TYPE_TXT = "file"
  const uidGenerator = () => {
    return '-' + parseInt(Math.random() * 10000 + 1, 10);
  }
  const getFileName = (path) => {
    if (path.lastIndexOf("\\") >= 0) {
      let reg = new RegExp("\\\\", "g");
      path = path.replace(reg, "/");
    }
    return path.substring(path.lastIndexOf("/") + 1);
  }
  export default {
    name: 'UploadWithMediaType',
    data() {
      return {
        spinning:false,
        uploadAction: window._CONFIG['domianURL'] + "/sys/common/uploadNew",
        headers: {},
        fileList: [],
        newFileList: [],
        uploadGoOn: true,
        previewVisible: false,
        //---------------------------- begin 图片左右换位置 -------------------------------------
        previewImage: '',
        containerId: '',
        top: '',
        left: '',
        moveDisplay: 'none',
        showMoverTask: false,
        moverHold: false,
        currentImg: '',
        //---------------------------- end 图片左右换位置 -------------------------------------
        options: {
          //目标上传 URL，默认POST
          target: window._CONFIG['domianURL'] + '/api/upload/chunk',
          //分块大小(单位：字节)
          chunkSize: '2048000',
          //上传文件时文件内容的参数名，对应chunk里的Multipart对象名，默认对象名为file
          fileParameterName: 'upfile',
          //失败后最多自动重试上传次数
          maxChunkRetries: 3,
          //是否开启服务器分片校验，对应GET类型同名的target URL
          testChunks: false,
          /*
              服务器分片校验函数，判断秒传及断点续传,传入的参数是Uploader.Chunk实例以及请求响应信息
              reponse码是successStatuses码时，才会进入该方法
              reponse码如果返回的是permanentErrors 中的状态码，不会进入该方法，直接进入onFileError函数 ，并显示上传失败
              reponse码是其他状态码，不会进入该方法，正常走标准上传
              checkChunkUploadedByResponse函数直接return true的话，不再调用上传接口
              */
          checkChunkUploadedByResponse: function(chunk, response_msg) {
            let objMessage = JSON.parse(response_msg);
            if (objMessage.skipUpload) {
              return true;
            }
            return (objMessage.uploadedChunks || []).indexOf(chunk.offset + 1) >= 0;
          },
        },
        fileStatusText: {
          success: '上传成功',
          error: '上传失败',
          uploading: '上传中',
          paused: '暂停',
          waiting: '等待上传',
          merging: '合并中',
          done: '完成'
        },

      }
    },
    props: {
      text: {
        type: String,
        required: false,
        default: "点击上传"
      },
      fileType: {
        type: String,
        required: false,
        default: FILE_TYPE_ALL
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath: {
        type: String,
        required: false,
        default: "temp"
      },
      value: {
        type: [String, Array],
        required: false
      },
      // update-begin- --- author:wangshuai ------ date:20190929 ---- for:Jupload组件增加是否能够点击
      disabled: {
        type: Boolean,
        required: false,
        default: false
      },
      // update-end- --- author:wangshuai ------ date:20190929 ---- for:Jupload组件增加是否能够点击
      //此属性被废弃了
      triggerChange: {
        type: Boolean,
        required: false,
        default: false
      },
      /**
       * update -- author:lvdandan -- date:20190219 -- for:Jupload组件增加是否返回url，
       * true：仅返回url
       * false：返回fileName filePath fileSize
       */
      returnUrl: {
        type: Boolean,
        required: false,
        default: true
      },
      number: {
        type: Number,
        required: false,
        default: 0
      },
      buttonVisible: {
        type: Boolean,
        required: false,
        default: true
      },
    },
    watch: {
      value: {
        immediate: true,
        handler() {
          let val = this.value
          if (val instanceof Array) {
            if (this.returnUrl) {
              this.initFileList(val.join(','))
            } else {
              this.initFileListArr(val);
            }
          } else {
            this.initFileList(val)
          }
        }
      }
    },
    computed: {
      isImageComp() {
        return this.fileType === FILE_TYPE_IMG
      },
      complistType() {
        return this.fileType === FILE_TYPE_IMG ? 'picture-card' : 'text'
      }
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN);
      //---------------------------- begin 图片左右换位置 -------------------------------------
      this.headers = { "X-Access-Token": token };
      this.containerId = 'container-ty-' + new Date().getTime();
      //---------------------------- end 图片左右换位置 -------------------------------------
    },

    methods: {
      initFileListArr(val) {
        if (!val || val.length == 0) {
          this.fileList = [];
          return;
        }
        let fileList = [];
        for (var a = 0; a < val.length; a++) {
          let url = getFileAccessHttpUrl(val[a].fileUrl);
          fileList.push({
            uid: uidGenerator(),
            name: val[a].fileName,
            mediaType: val[a].mediaType,
            fileSuffix: val[a].fileSuffix,
            size: val[a].fileSize,
            status: val[a].status || 'done',
            url: url,
            response: {
              status: "history",
              message: val[a].fileUrl
            }
          })
        }
        this.fileList = fileList
      },
      initFileList(paths) {
        if (!paths || paths.length == 0) {
          //return [];
          // update-begin- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
          this.fileList = [];
          return;
          // update-end- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
        }
        let fileList = [];
        let arr = paths.split(",")
        for (var a = 0; a < arr.length; a++) {
          let url = getFileAccessHttpUrl(arr[a]);
          fileList.push({
            uid: uidGenerator(),
            name: getFileName(arr[a]),
            status: 'done',
            url: url,
            response: {
              status: "history",
              message: arr[a]
            }
          })
        }
        this.fileList = fileList
      },
      handlePathChange() {
        let uploadFiles = this.fileList
        let path = ''
        if (!uploadFiles || uploadFiles.length == 0) {
          path = ''
        }
        let arr = [];
        for (var a = 0; a < uploadFiles.length; a++) {
          // update-begin-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
          if (uploadFiles[a].status === 'done') {
            arr.push(uploadFiles[a].response.message)
          } else {
            return;
          }
          // update-end-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
        }
        if (arr.length > 0) {
          path = arr.join(",")
        }
        console.log(444)
        console.log(arr)
        this.$emit('change', path);
      },
      beforeUpload(file) {
        this.uploadGoOn = true
        var fileType = file.type;
        if (this.fileType === FILE_TYPE_IMG) {
          if (fileType.indexOf('image') < 0) {
            this.$message.warning('请上传图片');
            this.uploadGoOn = false
            return false;
          }
        }
        //TODO 扩展功能验证文件大小
        return true
      },
      handleChange(info) {
        console.log("--文件列表改变--")
        if (!info.file.status && this.uploadGoOn === false) {
          info.fileList.pop();
        }
        let fileList = info.fileList
        if (info.file.status === 'done') {
          if (this.number > 0) {
            fileList = fileList.slice(-this.number);
          }
          if (info.file.response.success) {
            fileList = fileList.map((file) => {
              if (file.response) {
                let reUrl = file.response.message;
                file.url = getFileAccessHttpUrl(reUrl);
                const { fileSuffix, mediaType } = this.getFileMediaType(file);
                file.mediaType = mediaType;
                file.fileSuffix = fileSuffix;
              }
              return file;
            });
          } else {
            //找到目标文件，将status改为'error'
            const targetFile = getFileItem(info.file, fileList);
            targetFile.status = 'error';
            info.file.status = 'error';
          }
        }
        if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`);
        } else if (info.file.status === 'removed') {
          this.handleDelete(info.file)
        }
        this.fileList = fileList
        if (info.file.status === 'done' || info.file.status === 'removed') {
          //returnUrl为true时仅返回文件路径
          this.handleFileChange();
        }
      },
      handleDelete(file) {
        //如有需要新增 删除逻辑
        console.log(file)
      },
      handlePreview(file) {
        if (this.fileType === FILE_TYPE_IMG) {
          this.previewImage = file.url || file.thumbUrl;
          this.previewVisible = true;
        } else {
          location.href = file.url
        }
      },
      handleCancel() {
        this.previewVisible = false;
      },
      //---------------------------- begin 图片左右换位置 -------------------------------------
      moveLast() {
        //console.log(ev)
        //console.log(this.fileList)
        //console.log(this.currentImg)
        let index = this.getIndexByUrl();
        if (index == 0) {
          this.$message.warn('未知的操作')
        } else {
          let curr = this.fileList[index].url;
          let last = this.fileList[index - 1].url;
          let arr = []
          for (let i = 0; i < this.fileList.length; i++) {
            if (i == index - 1) {
              arr.push(curr)
            } else if (i == index) {
              arr.push(last)
            } else {
              arr.push(this.fileList[i].url)
            }
          }
          this.currentImg = last
          this.$emit('change', arr.join(','))
        }
      },
      moveNext() {
        let index = this.getIndexByUrl();
        if (index == this.fileList.length - 1) {
          this.$message.warn('已到最后~')
        } else {
          let curr = this.fileList[index].url;
          let next = this.fileList[index + 1].url;
          let arr = []
          for (let i = 0; i < this.fileList.length; i++) {
            if (i == index + 1) {
              arr.push(curr)
            } else if (i == index) {
              arr.push(next)
            } else {
              arr.push(this.fileList[i].url)
            }
          }
          this.currentImg = next
          this.$emit('change', arr.join(','))
        }
      },
      getIndexByUrl() {
        for (let i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i].url === this.currentImg || encodeURI(this.fileList[i].url) === this.currentImg) {
            return i;
          }
        }
        return -1;
      },
      //删除文件
      deleteFile(index) {
        this.fileList.splice(index, 1);
        this.handleFileChange();
      },
      //获取文件基本信息
      getFileMediaType(file) {
        const dotIndex = file.name.lastIndexOf('.');
        let fileSuffix, mediaType;
        if (dotIndex > -1) {
          // fileName = file.name.substring(0, dotIndex);
          fileSuffix = file.name.substring(dotIndex + 1);
        }
        if (isImgFile(fileSuffix)) {
          mediaType = '0'
        } else if (isVideoFile(fileSuffix)) {
          mediaType = '1'
        } else if (isAudioFile(fileSuffix)) {
          mediaType = '2'
        } else {
          mediaType = '3';
        }
        return { fileSuffix, mediaType };
      },
      handleFileChange() {
        if (this.returnUrl) {
          this.handlePathChange()
        } else {
          //returnUrl为false时返回文件名称、文件路径及文件大小
          this.newFileList = [];
          for (var a = 0; a < this.fileList.length; a++) {
            // update-begin-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
            const item = this.fileList[a];
            if (item.status === 'done') {
              var fileJson = {
                fileName: item.name,
                fileUrl: item.response.message,
                fileSize: item.size,
                fileSuffix: item.fileSuffix,
                mediaType: item.mediaType
              };
              this.newFileList.push(fileJson);
            } else {
              return;
            }
            // update-end-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
          }
          this.$emit('change', this.newFileList);
        }
      },
      // 上传
      onFileAdded(file) {
        this.computeMD5(file);
      },
      /*
    第一个参数 rootFile 就是成功上传的文件所属的根 Uploader.File 对象，它应该包含或者等于成功上传文件；
    第二个参数 file 就是当前成功的 Uploader.File 对象本身；
    第三个参数就是 message 就是服务端响应内容，永远都是字符串；
    第四个参数 chunk 就是 Uploader.Chunk 实例，它就是该文件的最后一个块实例，如果你想得到请求响应码的话，chunk.xhr.status就是
    */
      onFileSuccess(rootFile, file, response, chunk) {
        this.spinning = true
        //refProjectId为预留字段，可关联附件所属目标，例如所属档案，所属工程等
        file.refProjectId = "123456789";
        mergeFile(file).then(response => {

          let reUrl = response.result;
          console.log(reUrl)
          // this.returnUrl = reUrl
          file.url = getFileAccessHttpUrl(reUrl);
          const { fileSuffix, mediaType } = this.getFileMediaType(file);
          file.mediaType = mediaType;
          file.fileSuffix = fileSuffix;
          let fileList = [];
          let newfileList = [];

          let url = getFileAccessHttpUrl(reUrl);
          fileList.push({
            uid: uidGenerator(),
            name: getFileName(reUrl),
            status: 'done',
            url: url,
            response: {
              status: "history",
              message: reUrl
            }
          })
          // var fileJson = {
          //   fileName: getFileName(reUrl),
          //   fileUrl: reUrl,
          //   fileSize: item.size,
          //   fileSuffix:item.fileSuffix,
          //   mediaType:item.mediaType
          // };
          fileList = fileList.map((file) => {
            if (file.response) {
              let reUrl = reUrl;
              file.url = getFileAccessHttpUrl(reUrl);
              const { fileSuffix, mediaType } = this.getFileMediaType(file);
              file.mediaType = mediaType;
              file.fileSuffix = fileSuffix;
            }
            return file;
          });
          this.fileList = fileList
          this.newFileList = fileList
          this.handleFileChange();

          this.$emit('change', this.newFileList);
          this.spinning = false

        }).catch(function(error) {
          console.log("合并后捕获的未知异常：" + error);
        });
      },
      onFileError(rootFile, file, response, chunk) {
        console.log('上传完成后异常信息：' + response);
      },
      error(msg) {
        this.$notify({
          title: '错误',
          message: msg,
          type: 'error',
          duration: 2000
        })
      },
      /**
       * 计算md5，实现断点续传及秒传
       * @param file
       */
      computeMD5(file) {
        file.pause();
        //单个文件的大小限制0.5G
        let fileSizeLimit = 0.5 * 1024 * 1024 * 1024;
        console.log("文件大小：" + file.size);
        console.log("限制大小：" + fileSizeLimit);
        if (file.size > fileSizeLimit) {
          this.$message({
            showClose: true,
            message: '文件大小不能超过2G'
          });
          file.cancel();
        }
        let fileReader = new FileReader();
        let time = new Date().getTime();
        let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
        let currentChunk = 0;
        const chunkSize = 20 * 1024 * 1000;
        let chunks = Math.ceil(file.size / chunkSize);
        let spark = new SparkMD5.ArrayBuffer();
        //由于计算整个文件的Md5太慢，因此采用只计算第1块文件的md5的方式
        let chunkNumberMD5 = 1;
        loadNext();
        fileReader.onload = (e => {
          spark.append(e.target.result);
          if (currentChunk < chunkNumberMD5) {
            loadNext();
          } else {
            let md5 = spark.end();
            console.log(md5);
            file.uniqueIdentifier = md5;
            file.resume();
            console.log(`MD5计算完毕：${file.name} \nMD5：${md5} \n分片：${chunks} 大小:${file.size} 用时：${new Date().getTime() - time} ms`);
          }
        });

        fileReader.onerror = function() {
          this.error(`文件${file.name}读取出错，请检查该文件`)
          file.cancel();
        };

        function loadNext() {
          let start = currentChunk * chunkSize;
          let end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

          fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
          currentChunk++;
          console.log("计算第" + currentChunk + "块");
        }
      },
    },

    mounted() {
      const moverObj = document.getElementById(this.containerId + '-mover');
      if (moverObj) {
        moverObj.addEventListener('mouseover', () => {
          this.moverHold = true
          this.moveDisplay = 'block';
        });
        moverObj.addEventListener('mouseout', () => {
          this.moverHold = false
          this.moveDisplay = 'none';
        });
      }

      let picList = document.getElementById(this.containerId) ? document.getElementById(this.containerId).getElementsByClassName('ant-upload-list-picture-card') : [];
      if (picList && picList.length > 0) {
        picList[0].addEventListener('mouseover', (ev) => {
          ev = ev || window.event;
          let target = ev.target || ev.srcElement;
          if ('ant-upload-list-item-info' == target.className) {
            this.showMoverTask = false
            let item = target.parentElement
            this.left = item.offsetLeft
            this.top = item.offsetTop + item.offsetHeight - 50;
            this.moveDisplay = 'block';
            this.currentImg = target.getElementsByTagName('img')[0].src
          }

        });

        picList[0].addEventListener('mouseout', (ev) => {
          ev = ev || window.event;
          let target = ev.target || ev.srcElement;
          //console.log('移除',target)
          if ('ant-upload-list-item-info' == target.className) {
            this.showMoverTask = true
            setTimeout(() => {
              if (this.moverHold === false)
                this.moveDisplay = 'none';
            }, 100)
          }
          if ('ant-upload-list-item ant-upload-list-item-done' == target.className || 'ant-upload-list ant-upload-list-picture-card' == target.className) {
            this.moveDisplay = 'none';
          }
        })
        //---------------------------- end 图片左右换位置 -------------------------------------
      }
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style lang="less">
  .uploadty-disabled {
    .ant-upload-list-item {
      .anticon-close {
        display: none;
      }

      .anticon-delete {
        display: none;
      }
    }
  }

  //---------------------------- begin 图片左右换位置 -------------------------------------
  .uploadty-mover-mask {
    background-color: rgba(0, 0, 0, 0.5);
    opacity: .8;
    color: #fff;
    height: 28px;
    line-height: 28px;
  }

  //---------------------------- end 图片左右换位置 -------------------------------------
  .upload-list {
    list-style: none;
    margin: 0;
    padding: 0;
  }

  .file-delete {
    display: none;
    margin-right: 20px;
    color: red;
  }

  .file-item:hover .file-delete {
    display: unset;
  }

  .file-item-name {
    color: #1890FF;
    padding-left: 10px;
  }

  .error-file-item {
    color: red
  }
  .hint{
    color:red;
    font-size: 12px;
  }
</style>
